
import React, { useState } from 'react';
import DOMPurify from 'dompurify';
import * as SecurityUtil from './SecurityUtil';


function XSSDemo() {
  const [name, setName] = useState('');
  const [srcName, setSrcName] = useState('');
  const [htmlName, setHtmlName] = useState('');

  const [isSanitized, setIsSanitized] = useState(false);
  const [isUtilSanitized, setIsUtilSanitized] = useState(false);
  const [isHtmlSanitized, setIsHtmlSanitized] = useState(false);

  const [showNameClass, setShowNameClass] = useState('show-name-red');
  const [showSrcClass, setShowSrcClass] = useState('show-name-red');


  const handleChange = (e) => {
    const newName = isSanitized ? DOMPurify.sanitize(e.target.value) : e.target.value;
    setName(newName)
  }

  const handleSrcChange = (e) => {
    const newName = isUtilSanitized ? SecurityUtil.jsSanitize(e.target.value) : e.target.value;
    setSrcName(newName)

  }

  const handleHtmlChange = (e) => {
    const newName = isHtmlSanitized ? SecurityUtil.HtmlSanitize(e.target.value) : e.target.value;
    setHtmlName(newName)
  }

  const handleOpenChange = () => {
    setShowNameClass(isSanitized ? 'show-name-red' : 'show-name-green')
    setIsSanitized(!isSanitized)
  }

  const handleOpenUtilChange = () => {
    setShowSrcClass(isUtilSanitized ? 'show-name-red' : 'show-name-green')
    setIsUtilSanitized(!isUtilSanitized)
  }

  const handleOpenHTMLUtilChange = () => {
    setIsHtmlSanitized(!isHtmlSanitized)
  }

  return <div>
    <header>Web安全攻击攻防演练Demo</header>

    <div className='block'>1. 用户输入内容(image onerror)XSS攻击</div>
    <div className='open-sanitize'>
      <span>开启DomPurify防守:</span>
      <input type="checkbox" value={isSanitized} onChange={handleOpenChange}/>
    </div>

    <div>
      <span>输入用户名:</span>
      <input value={name} onChange={handleChange} ></input>
    </div>

    <div className={showNameClass}>显示用户名：
      <span dangerouslySetInnerHTML={{ __html: name }}></span>
    </div>

    <div className='block block-2'>2. 用户生成iframe的中src的XSS攻击</div>

    <div className='open-sanitize'>
      <span>开启SecurityUtil防守:</span>
      <input type="checkbox" value={isUtilSanitized} onChange={handleOpenUtilChange}/>
    </div>

    <div>
      <span>输入src:</span>
      <input value={srcName} onChange={handleSrcChange} ></input>
    </div>

    <div className={showSrcClass}>显示iframe：
      <div><iframe src={srcName} title='test'/></div>
    </div>

    <div className='block block-2'>3. HTML注入攻击</div>

    <div className='open-sanitize'>
      <span>开启HTML注入防守:</span>
      <input type="checkbox" value={htmlName} onChange={handleOpenHTMLUtilChange}/>
    </div>

    <div>
      <span>输入用户名:</span>
      <input value={htmlName} onChange={handleHtmlChange} ></input>
    </div>

    <div className='input-block'>显示用户名：
      <span dangerouslySetInnerHTML={{ __html: htmlName }}></span>
    </div>

  </div>
}
export default XSSDemo